/******************************************************************************
 * Copyright (C) 2016  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODE_UTIL_APPLICATION_H_
#define NODE_UTIL_APPLICATION_H_

#include <exception>
#include <string>
#include <vector>
#include <node/noncopyable.h>
#include <node/util/option_set.h>

namespace node {
    namespace util {

    class application : private noncopyable
    {
    public:
        application(const std::string& name);
        virtual ~application(void);

        static application* instance(void);
        const std::string& get_name(void);
        int run(int argc, char* argv[]);

    protected:
        void show_usage(void);
        bool hook_signal(int signal);
        bool ignore_signal(int signal);
        bool reset_signal(int signal);
        void hanle_exception(const std::exception& e);

        virtual void on_def_options(node::util::option_set& options) = 0;
        virtual int on_option(const std::string& name, const std::string& argument) = 0;
        virtual int on_init(void) = 0;
        virtual void on_uninit(void) = 0;
        virtual void on_signal(int signal) {}
        virtual int main(const std::vector<std::string>& unknown_arguments) = 0;

    private:
        int init(int argc, char* argv[]);
        void uninit(void);
        static void signal_handler(int signal);

        std::string _name;
        std::vector<std::string> _arguments;
        option_set _options;
        static application* _this;
    };
    inline application* application::instance(void) { return _this; }
    inline const std::string& application::get_name(void) { return _name; }

}}

#endif //NODE_UTIL_APPLICATION_H_
